import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import savePlugin from './sav-plugin'

Vue.use(Vuex)

// Store 仓库
const store = new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production', // 严格模式，不要在发布环境下启用严格模式，以免造成性能损失
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || [] // 购物车数组
  },
  getters: { // 类似组件的 computed
    // 是否全选
    allChecked(state) {
      return state.cart.every(prod => prod.checked)
    },
    // 计算选中商品的合计金额
    totalMoney(state) {
      return state.cart.reduce((sum, prod) => {
        if (prod.checked) {
          sum += prod.amount * prod.price * 100
        }
        return sum
      }, 0)
    },
    // 购物车中商品总数量
    totalAmount(state) {
      return state.cart.reduce((sum, prod) => (sum += prod.amount), 0)
    }
  },
  mutations,
  actions: {},
  modules: {},
  plugins: [savePlugin]
})

export default store
